<template>
  <div class="profile-actions-container">
    <el-tabs v-model="activeTab" class="profile-tabs">
      <el-tab-pane label="收藏夹" name="favorites">
        <div v-loading="loading" class="favorites-list">
          <!-- 收藏夹不公开的提示 -->
          <el-alert
            v-if="!isFavoritesPublic"
            title="该用户的收藏夹为隐私状态"
            type="warning"
            :closable="false"
            show-icon
          >
            只有用户本人可以查看收藏夹
          </el-alert>

          <el-empty
            v-else-if="favorites.length === 0"
            description="暂无收藏"
          />

          <div v-else-if="isFavoritesPublic" class="favorites-grid">
            <el-card v-for="post in favorites" :key="post.id" class="favorite-card">
              <div class="favorite-header">
                <div class="user-info">
                  <div class="user-meta">
                    <span class="username">{{ post.user.username }}</span>
                    <span class="post-time">
                      <el-icon><Clock /></el-icon>
                      {{ formatTime(post.created_at) }}
                    </span>
                  </div>
                </div>
                <el-tag
                  :type="getTagType(post.topic)"
                  effect="light"
                  class="topic-tag"
                >
                  {{ post.topic }}
                </el-tag>
              </div>

              <div class="favorite-content" @click="openPostDetail(post)">
                <h3 class="content-title">{{ extractTitle(post.content) }}</h3>
                <p class="content-preview">{{ getPreviewContent(post.content) }}</p>
              </div>

              <div class="favorite-stats">
                <div class="stats-item">
                  <el-icon><ChatRound /></el-icon>
                  <span>{{ postCommentsCount[post.id] || 0 }} 评论</span>
                </div>
              </div>

              <div class="favorite-actions">
                <el-button
                  type="primary"
                  link
                  class="action-button"
                  @click="openPostDetail(post)"
                >
                  <el-icon><View /></el-icon>
                  查看详情
                </el-button>
                <el-button
                  v-if="isCurrentUser"
                  type="danger"
                  link
                  class="action-button"
                  @click.stop="handleUnfavorite(post)"
                >
                  <el-icon><Star /></el-icon>
                  取消收藏
                </el-button>
              </div>
            </el-card>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 帖子详情弹窗 -->
    <el-dialog
      v-model="showPostDetail"
      title="帖子详情"
      width="800px"
      :before-close="closePostDetail"
      class="post-detail-dialog"
    >
      <PostDetail
        v-if="currentPost"
        :post="currentPost"
        :current-user="currentUser"
        :is-teacher="currentUser.role === 'teacher'"
        @back="closePostDetail"
        @update:post="handlePostUpdate"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star, Clock, ChatRound, View } from '@element-plus/icons-vue'
import PostDetail from "@/components/CourseDiscussion/PostDetail.vue";
import axios from 'axios'

const props = defineProps({
  userId: {
    type: String,
    required: true
  },
  currentUser: {
    type: Object,
    required: true
  }
})

const isCurrentUser = ref(false)
const activeTab = ref('favorites')
const loading = ref(false)
const favorites = ref([])
const showPostDetail = ref(false)
const currentPost = ref(null)
const postCommentsCount = ref({})

//收藏夹是否公开的状态
const isFavoritesPublic = ref(false)

onMounted(() => {
  isCurrentUser.value = props.currentUser.id === props.userId
  fetchUserProfile()
})


//获取用户信息
const fetchUserProfile = async () => {
  try {
    const response = await axios.get(`/backend/api/account/profile/${props.userId}/`, {
      withCredentials: true
    })

    // 判断收藏夹是否公开
    isFavoritesPublic.value = response.data.is_favorites_public || isCurrentUser.value

    // 如果收藏夹公开或是当前用户，才获取收藏列表
    if (isFavoritesPublic.value) {
      await fetchFavorites()
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}


//获取收藏列表
const fetchFavorites = async () => {
  loading.value = true
  try {
    const response = await axios.get(`/backend/api/post/users/${props.userId}/favorites/`, {
      withCredentials: true
    })
    favorites.value = response.data
    await Promise.all(favorites.value.map(fetchPostCommentsCount))
  } catch (error) {
    if (error.response && error.response.data.error) {
      ElMessage.warning(error.response.data.error)
    } else {
      ElMessage.error('获取收藏列表失败')
    }
  } finally {
    loading.value = false
  }
}
//获取帖子评论数量
const fetchPostCommentsCount = async (post) => {
  try {
    const response = await axios.get(`/backend/api/post/${post.id}/comments/`, {
      withCredentials: true
    })
    postCommentsCount.value[post.id] = response.data.length
  } catch (error) {
    console.error(`获取帖子 ${post.id} 评论数量失败:`, error)
    postCommentsCount.value[post.id] = 0
  }
}


//收藏/取消收藏
const handleUnfavorite = async (post) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏这篇帖子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.post(
      `/backend/api/post/${post.id}/unfavorite/`,
      {},
      { withCredentials: true }
    )

    if (response.data.message) {
      ElMessage.success('已取消收藏')
      await fetchFavorites()
    }
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('取消收藏失败')
  }
}

const getTagType = (topic) => {
  const types = {
    '问题': 'danger',
    '分享': 'success',
    '讨论': 'warning',
    '建议': 'info'
  }
  return types[topic] || 'info'
}

const extractTitle = (content) => {
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(content, 'text/html')
    const titleElement = doc.querySelector('title')
    return titleElement ? titleElement.textContent : '无标题'
  } catch (e) {
    return '无标题'
  }
}

const getPreviewContent = (content) => {
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(content, 'text/html')
    const paragraphs = doc.querySelectorAll('p')
    let previewText = ''
    for (let i = 0; i < paragraphs.length && previewText.length < 200; i++) {
      previewText += paragraphs[i].textContent + ' '
    }
    return previewText.slice(0, 200) + (previewText.length > 200 ? '...' : '')
  } catch (e) {
    return '内容解析失败'
  }
}

const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
//获取帖子详情
const openPostDetail = async (post) => {
  try {
    const response = await axios.get(`/backend/api/post/${post.id}/`, {
      withCredentials: true
    })
    currentPost.value = response.data
    showPostDetail.value = true
  } catch (error) {
    ElMessage.error('获取帖子详情失败')
  }
}

const closePostDetail = () => {
  showPostDetail.value = false
  currentPost.value = null
}

const handlePostUpdate = (updatedPost) => {
  const index = favorites.value.findIndex(p => p.id === updatedPost.id)
  if (index !== -1) {
    favorites.value[index] = updatedPost
  }
  currentPost.value = updatedPost
}
</script>

<style scoped>
.profile-actions-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.profile-tabs {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  padding: 16px;
}

.favorite-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.favorite-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.favorite-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.username {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.post-time {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.topic-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

.favorite-content {
  flex-grow: 1;
  cursor: pointer;
  padding: 16px 0;
}

.content-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.content-preview {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 16px;
}

.favorite-stats {
  display: flex;
  gap: 16px;
  padding: 12px 0;
  border-top: 1px solid #f0f2f5;
}

.stats-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 13px;
}

.favorite-actions {
  display: flex;
  justify-content: space-between;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.post-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

@media (max-width: 768px) {
  .profile-actions-container {
    padding: 16px;
  }

  .favorites-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}
</style>